<template>
  <div>
    <div class="search">
      <input type="text" v-model="keyword" class="search-input" placeholder="请输入拼音或城市名" />
    </div>
    <div class="search-content" ref="searchRes" v-show="keyword">
      <ul>
        <li class="search-item border-bottom" v-for="item of list" :key="item.id" @click="handCity(item.name)">
          {{item.name}}
        </li>
        <li class="search-item border-bottom" v-show="hasNoData">
          没有找到相关数据
        </li>
      </ul>
    </div>
  </div>
</template>

<script>
import { mapMutations } from 'vuex'
import BScroll from 'better-scroll'
export default {
  name: 'CitySearch',
  props: { // 接收父组件传过来的参数
    cities: Object
  },
  data () {
    return {
      keyword:'',
      list: [],
      timer: null
    }
  },
  watch: { // 监听keyword的变化
    keyword () {
      if (this.timer) { // 如果有定时器就清除
        clearInterval(this.timer)
      }
      if (!this.keyword) {
        this.list = []
        return
      }
      this.timer = setTimeout(() => { // 这里做下函数节流
        const result = [] // 定义一个空数组来接收结果
        for (let i in this.cities) { // 循环遍历cities
          this.cities[i].forEach((value) => { // 再循环一遍
            if (value.spell.indexOf(this.keyword) > -1 || value.name.indexOf(this.keyword) > -1) { // 找下有没有这么东西
                result.push(value) // 有就push
            }
          })
        }
        this.list = result // 将结果赋值一下
      }, 100)
    }
  },
  methods: {
    handCity (city) {
      // 调用Vuex的dispatch派发到actions,但是必须调用actions来修改store的数据
      // this.$store.dispatch('changeCity',city)
      // 直接调用Vuex commit 方法不需要经过actions来修改store的数据
      // this.$store.commit('changeCity', city)
      this.changeCity(city)
      this.$router.push('/') // 编程试路由
    },
    ...mapMutations(['changeCity'])
  },
  mounted() { // 解决页面不能滑动的问题
    this.scroll = new BScroll(this.$refs.searchRes)
  },
  computed: {
    hasNoData () {
      return !this.list.length // 判断this.list.length是否为空
    }
  }
}
</script>

<style lang="less" scoped>
  @import "~styles/varlibase.less";
  .search{
    height: .72rem;
    padding: 0 .1rem;
    background-color: @bgColor;
    .search-input{
      box-sizing: border-box;
      height: .62rem;
      width: 100%;
      line-height: .62rem;
      border-radius: .06rem;
      text-align: center;
      color: #666;
      padding: 0 .1rem;
      font-family: 'Microsoft Yahei'
    }
  }
  .search-content{
    overflow: hidden;
    background-color: #eee;
    z-index:1;
    position: absolute;
    top: 1.58rem;
    left: 0;
    right: 0;
    bottom: 0;
    .search-item{
      line-height: 0.62rem;
      padding-left: .2rem;
      color:#666;
      background-color: #fff;
    }
  }
</style>
